/*
 * Copyright (c) 2024 -present FengJinjian ( 751965763@qq.com )
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * UserServiceImpl
 *
 * @version 1.0.1
 * @author FengJinJian
 * @date 2024/03/19 10:00
 */
package edu.vital.energy.longevity.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.vital.energy.longevity.domain.dto.LoginDTO;
import edu.vital.energy.longevity.domain.dto.LoginedDTO;
import edu.vital.energy.longevity.domain.entity.User;
import edu.vital.energy.longevity.mapper.UserMapper;
import edu.vital.energy.longevity.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public LoginedDTO login(LoginDTO loginDTO) {

        System.out.printf(loginDTO.username());
        User user = this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, loginDTO.username()));
        if (user == null) {
            throw new IllegalArgumentException("User not found");
        }
        if (user == null) {
            throw new IllegalArgumentException("User not found");
        }
        
        if (!user.getPassword().equals(loginDTO.password())) {
            throw new IllegalArgumentException("Invalid password");
        }

        
        // Login with sa-token
        StpUtil.login(user.getId());
        return  new LoginedDTO(StpUtil.getTokenInfo().getTokenName(),StpUtil.getTokenInfo().getTokenValue(),
                StpUtil.getTokenInfo().getLoginId(),user.getUsername(),user.getNickName(),StpUtil.getTokenInfo().getLoginType());
    }
} 